package com.wac.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wac.data.entity.Like;
import com.wac.data.entity.Message;
import com.wac.data.mapper.*;
import com.wac.data.service.LikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author beta
 * @since 2023-03-16
 */
@Service
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Like> implements LikeService {

	@Resource
	private LikeMapper likeMapper;
	@Resource
	private MessageMapper messageMapper;
	@Resource
	private DynamicMapper dynamicMapper;
	@Resource
	private CommentMapper commentMapper;
	@Resource
	private CriticismMapper criticismMapper;


	@Override
	public boolean isLike(String userId, String entityId) {
		if (userId == null) {
			return false;
		}
		if (likeMapper.selectOne(new QueryWrapper<Like>().eq("like_id", userId).eq("entity_id", entityId)) != null) {
			return true;
		}
		return false;
	}

	@Override
	public boolean toLike(String userId, String entityId, String type) {
		if (userId == null) {
			return false;
		}
		Like like = new Like();
		String belongId = null;
		System.out.println(type);
		if (type.equals("dynamic")) {
			belongId = dynamicMapper.selectById(entityId).getUserId();
		} else if (type.equals("criticism")) {
			belongId = criticismMapper.selectById(entityId).getUserId();
		} else {
			belongId = commentMapper.selectById(entityId).getUserId();
		}
		if (isLike(userId, entityId)) {
			if (!(userId.equals(belongId))) {
				if (messageMapper.delete(new QueryWrapper<Message>().eq("send_id", userId).eq("source", entityId).eq("type", "like")) == 1 && likeMapper.delete(new QueryWrapper<Like>().eq("like_id", userId).eq("entity_id", entityId)) == 1) {
					return true;
				}
			} else {
				if (likeMapper.delete(new QueryWrapper<Like>().eq("like_id", userId).eq("entity_id", entityId)) == 1) {
					return true;
				}
			}
			return false;
		}
		like.setLikeId(userId);
		like.setEntityId(entityId);
		like.setType(type);

		if (likeMapper.insert(like) == 1) {
			return true;
		}
		return false;
	}

	@Override
	public boolean delete(String id) {
		likeMapper.delete(new QueryWrapper<Like>().eq("entity_id", id));
		return true;
	}
}
